package com.axend.aerosense.dev.viewmodel;

import android.util.Base64;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.WsApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.dev.entity.BreathAndHeartBean;
import com.axend.aerosense.dev.entity.DevRadarSettingResBean;
import com.axend.aerosense.dev.entity.RadarInsatllTipsBean;
import com.axend.aerosense.dev.entity.RadarNetworkBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.network.websocket.JWebSocketClient;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.net.URI;
import java.nio.ByteBuffer;

import io.reactivex.disposables.Disposable;
import lombok.Data;
import lombok.Getter;


@Getter
public class CheckRoomViewModel extends CustomBaseViewModel<BaseBean> {
    private MutableLiveData<Boolean> isDevOnLine = new MutableLiveData<>(true);
    private MutableLiveData<Boolean> isInRoom = new MutableLiveData<>(true);
    private String radarId;
    //WebSocket
    private JWebSocketClient client;

    public void setRadarId(String radarId){
        this.radarId = radarId;
        initWebSocket();
    }

    public CheckRoomViewModel(IBaseView baseViewImpl, ILoadDataResult<BaseBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
    }

    public JWebSocketClient getClient() {
        return client;
    }

    public void setClient(JWebSocketClient client) {
        this.client = client;
    }

    @Override
    public void onLoad() {
        loadDataSuccess(null);

    }

    private void initWebSocket(){
        String token = MmkvHelper.getInstance().getMmkv().decodeString(Gobal.SAVE_KEY.TOKEN);
        URI uri = WsApi.getRespiratoryHeartRateSyncURI(token, radarId);
        client = new JWebSocketClient.Builder(uri,(message -> {
            LogUtils.d("message:", message);
            BreathAndHeartBean bean = JsonUtil.toObject(message, BreathAndHeartBean.class);
            if (1000 == bean.getFunction()) {
                byte[] decode = Base64.decode(bean.getData(), 0);
                ByteBuffer wrap = ByteBuffer.wrap(decode);
                // 呼吸BPM float
                float breatheBPM = wrap.getFloat();
                //    呼吸曲线 float
                float breatheCurve = wrap.getFloat();
                //    心率BPM float
                float heartBPM = wrap.getFloat();
                //    心率曲线 float
                float heartCurve = wrap.getFloat();
                //    目标距离 float  可用于离床、在床判断
                float targetDistance = wrap.getFloat();
                //    目标信号强度（用于存在检测）float  可用于离床、在床判断
                float targetStrength = wrap.getFloat();
                //    阶段检测 int
                int detection = wrap.getInt();
                if (0 == targetStrength && 0 == targetDistance && isInRoom.getValue() != null && isInRoom.getValue()) {
                    isInRoom.postValue(false);
                }
                if (isInRoom.getValue() != null && !isInRoom.getValue() && 0 < targetDistance && 0 < targetStrength) {
                    isInRoom.postValue(true);
                }
            }
        })).builder();
    }

    @Override
    protected void onCleared() {
        if(getClient() != null && getClient().isOpen()){
            getClient().closeConnectByUser();
        }
        super.onCleared();
    }
}
